/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trial.request;

/**
 *
 * @author feifei
 */
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ejb.Stateless;
import javax.ejb.EJBException;
import trial.entity.Customer;
import trial.entity.CustomerAddr;
import trial.entity.CustomerIdentity;
import trial.entity.Item;
import trial.entity.OrderSet;
import trial.entity.Sell;
import trial.entity.Sell_FixedPrice;
import trial.entity.Shop;
import trial.entity.SingleOrder;

@Stateless
public class RequestBean implements Request{
    private static final Logger logger = Logger.getLogger("trial.request.RequestBean");
    @PersistenceContext
    EntityManager em;
    
    public RequestBean(){}
    
   
    @Override
    public Long createItem(String name) {
        //throw new UnsupportedOperationException("Not supported yet.");
    
      try{
            em.getTransaction().begin();
            Item itemInstance = new Item();
            itemInstance.setName(name);
            em.persist(itemInstance);
            em.getTransaction().commit();
            logger.log(Level.INFO, "create item with id {0}", itemInstance.getId());
        
            return itemInstance.getId();
      
      } catch (Exception ex) {
           
            throw new EJBException(ex);
        }
    }
    @Override
    public void updateItem(Long item,String newName)
    {
        try
        {
        em.getTransaction().begin();
        Item iteminstance = em.find(Item.class,item);   
        iteminstance.setName(newName);
        em.getTransaction().commit();
        logger.log(Level.INFO, "item{0} exist and updated", item);
        } catch (Exception ex) {
           
            throw new EJBException(ex.getMessage());
        }
     }
    
        @Override
    public void deleteItem(Item item) {
        Item temp=em.find(Item.class,item.getId());
        em.remove(temp);
        
    }

    @Override
    public void updateItem(Item item, String newname) {
        try{
            Item temp=em.find(Item.class, item.getId());
            temp.setName(newname);
            }catch(Exception e)
            {
                throw new EJBException(e);
            }
    }
    
    
    
    @Override
    public List<Item> showAllItems() {
       // throw new UnsupportedOperationException("Not supported yet.");
     
     List<Item> items=(List<Item>) em.createQuery("SELECT i FROM Item i").getResultList();
    
    for(Item i:items)
    {
        i=em.merge(i);
        i.getSells().size();
    }   
            return items;
    }
    
    
    
    
     @Override
    public Long createSell_FixedPrice(Long shopId,Long itemId, Long price,Long storage) {
        //throw new UnsupportedOperationException("Not supported yet.");
        try{    em.getTransaction().begin();            
                Shop shop=em.find(Shop.class, shopId);
                Item item=em.find(Item.class, itemId);
                Sell priceInstance = new Sell_FixedPrice(shop,item,price,storage);
                em.persist(priceInstance);
                em.getTransaction().commit();
                return shop.getId();
            } catch (Exception ex) {
            throw new EJBException(ex.getMessage());
        }
       
    }
   


    @Override
    public void updateSell_FixedPrice(Long sellId, Long price,Long storage) {
        //throw new UnsupportedOperationException("Not supported yet.");
      try{
          em.getTransaction().begin();
          Sell_FixedPrice temp=em.find(Sell_FixedPrice.class,sellId);
          temp.setPrice(price);
          temp.setStorage(storage);
          em.getTransaction().commit();
          logger.log(Level.INFO, "update price for sell", temp);
         }
      catch (Exception e) {
             throw new EJBException(e.getMessage());
            }
      }
 
    @Override
    public List<Sell_FixedPrice> showAllSells_FixedPrice()
    {
        List<Sell_FixedPrice> sells=(List<Sell_FixedPrice>) em.createQuery("SELECT i FROM Sell_FixedPrice i").getResultList();
        return sells;
    }
 
    @Override
    public Long createCustomer(String name, String country, String zipcode,String bankaccount,String email, String password) {
        try{
            System.out.println("createCustomer Test****************************"+ name+ country);
             CustomerAddr addr=new CustomerAddr(country,zipcode);
             CustomerIdentity customerId= new CustomerIdentity(email,password);
             Customer customer=new Customer(name,customerId,addr,bankaccount);
             em.persist(customer);         
             return customer.getId();
           }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
        
    }
    @Override
    public Boolean identifyCustomer(String email,String password)
    {
        try{
            
        CustomerIdentity inputId =new CustomerIdentity(email,password);
        List<Customer> customers=em.createNamedQuery("Customer.findCustomer").setParameter("inputId", inputId).getResultList();
        if(customers.isEmpty())
            return false;
        else if(customers.size()==1&&customers.get(0).getCustomerId().equals(inputId))
            return true;
        else
            return false;
    
        
        
        }catch(Exception e)
        {
         throw new EJBException(e.getMessage());   
        }
              

        
        }
    
    @Override
    public void updateCustomer(Customer customer, String name, String country, String zipcode) {
        try{
            em.getTransaction().begin();
            Customer temp=em.find(Customer.class, customer.getId());
            temp.setName(name);
            temp.setAddress(new CustomerAddr(country,zipcode));
            em.getTransaction().commit();
            
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }

    @Override
    public void deleteCustomer(Long id) {
        System.out.println("RequestBean Test******"+id);
        try{
            Customer temp=em.find(Customer.class,id);
            em.remove(temp);            
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }

    @Override
    public Long createShop(Long ownerId, String shopName, String shopDescription) {
        try{
            em.getTransaction().begin();
            Customer owner=em.find(Customer.class, ownerId);
            Shop shop=new Shop(owner,shopName,shopDescription);
            owner.getAllShops().add(shop);
            em.persist(shop);
            em.getTransaction().commit();
            return shop.getId();
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }

    @Override
    public void deleteShop(Shop shop) {
        try{
            em.getTransaction().begin();
            Shop temp=em.find(Shop.class,shop.getId());
            em.remove(temp);
            em.getTransaction().commit();
            
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }

    @Override
    public void updateShop(Shop shop, String shopDescription) {
       try{
            em.getTransaction().begin();
            Shop temp=em.find(Shop.class, shop.getId());
            temp.setShopDescription(shopDescription);
            
            em.getTransaction().commit();
            
       }catch(Exception e)
       {
            throw new EJBException(e.getMessage());
       }
    }

    @Override
    public Long createOrder(Long ordersetId, Long sellId, Long quantity) {
       try{
            em.getTransaction().begin();
            OrderSet orderset=em.find(OrderSet.class, ordersetId);
            Sell sell=em.find(Sell.class,sellId);
            SingleOrder order=new SingleOrder(orderset,sell,quantity);
            orderset.getOrders().add(order);
            em.persist(order);
            em.getTransaction().commit();
            return order.getId();
         }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }

    @Override
    public void deleteOrder(Long orderId) {
        try{
            em.getTransaction().begin();
            SingleOrder temp=em.find(SingleOrder.class, orderId);
            em.remove(temp);
            em.getTransaction().commit();
            
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }

    @Override
    public void updateOrder(Long orderId,Long quantity) {
        try{
            em.getTransaction().begin();
            SingleOrder temp=em.find(SingleOrder.class, orderId);
            temp.setQuantity(quantity);
            em.getTransaction().commit();
            
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }

    @Override
    public Long createOrderSet(Long customerId, Long shopId) {
     try{
            em.getTransaction().begin();
            Customer customer=em.find(Customer.class,customerId);
            Shop shop=em.find(Shop.class,shopId);
            OrderSet orderset=new OrderSet(customer,shop);
            customer.getAllOrders().add(orderset);
            shop.getOrderList().add(orderset);
            em.persist(orderset);
            em.getTransaction().commit();
            return orderset.getId();
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }
    
    
    @Override
    public void removeOrderSet(OrderSet orderset) {
        try{
            em.getTransaction().begin();
            OrderSet temp=em.find(OrderSet.class,orderset.getId());
            em.remove(temp);
            em.getTransaction().commit();
            
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }

    }

    @Override
    public List<Customer> showAllCustomer() {
        try
        {
           List<Customer> customers= em.createNamedQuery("Customer.findAll").getResultList();
           return customers;
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }

    @Override
    public List<Shop> showAllShopOfOneCustomer(Customer customer) {
        try
        {
          List<Shop> shops= em.createNamedQuery("Shop.findAllShopsOfOnecustomer").setParameter("id", customer.getId()).getResultList();
          return shops;  
        }catch(Exception e)
        {
            throw new EJBException(e.getMessage());
        }
    }




}
